package com.lixin.smartclassroom.ui.home.tab5.activity

import android.net.Uri
import android.provider.MediaStore
import androidx.core.view.isNotEmpty
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeNetLife
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lixin.smartclassroom.api.getmyclassdetail
import com.lixin.smartclassroom.api.updateclass
import com.lixin.smartclassroom.api.uploadFile
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityEditClassBinding
import com.lixin.smartclassroom.ui.home.adapter.selectImages
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.load
import com.lixinkeji.extension.loadCircle
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.requestPerm
import com.lixinkeji.extension.text
import com.lixinkeji.extension.toast
import com.lixinkeji.utils.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File
import java.util.ArrayList

/**
 * Description 编辑资料
 * Author: lwc
 * Date:2023/12/11 14:05
 */
class EditClassAct : BaseActivity<ActivityEditClassBinding>() {
    override fun getViewBinding() = ActivityEditClassBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    override fun title() = "编辑资料"
    var size = 0
    private lateinit var classid: String
    private lateinit var imgUrl: String
    private var uploadFinishFlag = true

    override fun iniView() {
        classid = getIntentString("classid")
        scopeNetLife {
            val baseBean = getmyclassdetail(classid)
            if (baseBean.result == "0") {
                binding.apply {
                    imgUrl = baseBean.image!!
                    etClassName.setText(baseBean.title)
                    img.load(baseBean.image)
                }
            }
        }
    }


    override fun onClick() {
        binding.apply {
            img.onClick {
                requestPerm({
                    add(Permission.READ_MEDIA_IMAGES)
                    add(Permission.CAMERA)
                    add(Permission.WRITE_EXTERNAL_STORAGE)
                }, onGranted = { _, _ ->
                    selectPicture()
                }, onDenied = { permissions, never ->
                    if (never) {
                        saveSuccessDialog("获取相册权限失败")
                        XXPermissions.startPermissionActivity(
                            this@EditClassAct, permissions
                        )
                    } else {
                        saveSuccessDialog("获取相册权限失败")
                    }
                })
            }

            btnSave.onClick {
                if (!uploadFinishFlag) {
                    toast("请等待图片上传成功后提交")
                    return@onClick
                }
                if (etClassName.text().isEmpty()) {
                    toast("请输入班级名称")
                    return@onClick
                }
                scopeNetLife {
                    updateclass(etClassName.text(), imgUrl,classid)
                    sendEvent("cs","refreshClassData")
                    finish()
                }
            }
        }

    }

    private fun selectPicture() {
        PictureSelector.create(this@EditClassAct)
            .openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
            .setMinSelectNum(0)// 最小选择数量
            .setImageSpanCount(4)// 每行显示个数
            .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
            .isPreviewImage(true)// 是否可预览图片
            .isCameraAroundState(true)// 是否显示拍照按钮
            .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        if (result.size > 0) {
                            uploadFinishFlag = false
                            binding.img.loadRound(result[0].path!!, 10, true)
                            var file: File
                            if (result[0].path!!.contains("content:")) {
                                var res = ""
                                var proj = arrayOf(MediaStore.Images.Media.DATA)
                                val cursor = getContentResolver().query(
                                    Uri.parse(result[0].path!!),
                                    proj,
                                    null,
                                    null,
                                    null
                                );
                                if (cursor?.moveToFirst() == true) {
                                    val column_index =
                                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                    res = cursor.getString(column_index);
                                }
                                cursor?.close()
                                file = File(res)
                            } else {
                                file = File(result[0].path!!)
                            }

                            scopeNetLife {
                                val baseBean = uploadFile(file)
                                if (baseBean.result == "0") {
                                    imgUrl = baseBean.url.toString()
                                    uploadFinishFlag = true
                                }
                            }
                        }
                    }


                }

                override fun onCancel() {

                }
            })

    }

}